﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Top.Common;
using Top.Data;
using Top.PointStore.Business.Models;

namespace Top.PointStore.Business
{
    public class ChartManager
    {
        private static string PointReportApiUrl = Top.Common.TopConfigHelper.GetAppSettings("PointReportApi");
        private static TopWebUtils topWebUtils = new TopWebUtils();

        public static string  Get_PointReport_Data(string reportType,string daysNum)
        {
            string apiUrl = string.Empty;

            switch (reportType)
            {
                case "tag":
                    apiUrl = "get/tag_count";
                    break;
                case "pv":
                    apiUrl = "get/pv_count";
                    break;
                case "uv":
                    apiUrl = "get/uv_count";
                    break;
                case "ip":
                    apiUrl = "get/ip_count";
                    break;
            }
             Dictionary<string, string> dicPara = new Dictionary<string, string>();
            dicPara.Add("days_num", daysNum);
            string str = topWebUtils.DoGet(string.Format("{0}{1}", PointReportApiUrl, apiUrl), dicPara);
            return str;//topWebUtils.DoGet(string.Format("{0}{1}", PointReportApiUrl, apiUrl),dicPara);
        }

        public static async Task<string> PV_GetOneDay(DateTime day, string city, T_PointStoreAdminAuthority auth)
        {
            #region SQL
            string sql = @"
                SELECT timelist.htime AS description,
                       COUNT(A.F_MessageKey)AS COUNT
                FROM timelist
                LEFT JOIN
                  (SELECT F_MessageKey,
                          F_VisitHour
                   FROM T_PointStoreVisitLog
                   WHERE 1=1
                     AND F_VisitTime>={0}
                     AND F_VisitTime<{1} {2}) a ON timelist.htime=a.F_VisitHour
                GROUP BY timelist.htime
                        "; 
            #endregion
            List<Model_Chart> list = new List<Model_Chart>();
            if (auth.F_CityKid!=0)
            {
                city = auth.F_CityName;
            }
            if (!string.IsNullOrWhiteSpace(city))
            {
                string cityPart = " AND F_City={2}";
                sql = string.Format(sql, "{0}", "{1}", cityPart);
                using (var db = new DbTour())
                {
                    list = await db.Sql(sql, day.ToString("yyyy-MM-dd"), day.AddDays(1).ToString("yyyy-MM-dd"), city).ToList<Model_Chart>();
                }
            }
            else
            {
                sql = string.Format(sql, "{0}", "{1}", city);
                using (var db = new DbTour())
                {
                    list = await db.Sql(sql, day.ToString("yyyy-MM-dd"), day.AddDays(1).ToString("yyyy-MM-dd")).ToList<Model_Chart>();
                }
            }                 
            string str = Json.ToJsonString(new { data = list });
            return str;
        }

        public static async Task<string> PV_GetNDay(string startTime, string endTime, string city , T_PointStoreAdminAuthority auth)
        {
            #region SQL
            string sql = @"
                        select
                          date(F_VisitTime) as description,
                          COUNT(F_MessageKey)as count
                        from T_PointStoreVisitLog
                        WHERE 1=1
                          AND F_VisitTime>={0}
                          AND F_VisitTime<{1}
                         {2}
                        group by date(F_VisitTime)
                        "; 
            #endregion
            List<Model_Chart> list = new List<Model_Chart>();
            if (auth.F_CityKid != 0)
            {
                city = auth.F_CityName;
            }
            if (!string.IsNullOrWhiteSpace(city))
            {
                string cityPart = " AND F_City={2}";
                sql = string.Format(sql, "{0}", "{1}", cityPart);
                using (var db = new DbTour())
                {
                    list = await db.Sql(sql, startTime, endTime, city).ToList<Model_Chart>();
                }
            }
            else
            {
                sql = string.Format(sql, "{0}", "{1}", city);
                using (var db = new DbTour())
                {
                    list = await db.Sql(sql, startTime, endTime).ToList<Model_Chart>();
                }
            }     
            foreach (Model_Chart item in list)
            {
                item.description = item.description.Split(new string[] { " " },StringSplitOptions.RemoveEmptyEntries)[0].ToString();
            }
            string str = Json.ToJsonString(new { data = list });
            return str;
        }

        public static async Task<string> PV_GetOneYear(string startTime, string endTime, string city, T_PointStoreAdminAuthority auth)
        {
            #region SQL
            string sql = @"
                    SELECT yearlist.ytime AS description,
                           COUNT(A.F_MessageKey)AS COUNT
                    FROM yearlist
                    LEFT JOIN
                      ( SELECT F_MessageKey,
                               F_VisitMonth
                       FROM T_PointStoreVisitLog
                       WHERE 1=1
                         AND F_VisitTime>={0}
                         AND F_VisitTime<{1} {2} )A ON yearlist.ytime=a.F_VisitMonth
                    GROUP BY yearlist.ytime
                        "; 
            #endregion
            List<Model_Chart> list = new List<Model_Chart>();
            if (auth.F_CityKid != 0)
            {
                city = auth.F_CityName;
            }
            if (!string.IsNullOrWhiteSpace(city))
            {
                string cityPart = " AND F_City={2}";
                sql = string.Format(sql, "{0}", "{1}", cityPart);
                using (var db = new DbTour())
                {
                    list = await db.Sql(sql, startTime, endTime, city).ToList<Model_Chart>();
                }
            }
            else
            {
                sql = string.Format(sql, "{0}", "{1}", city);
                using (var db = new DbTour())
                {
                    list = await db.Sql(sql, startTime, endTime).ToList<Model_Chart>();
                }
            }     
            string str = Json.ToJsonString(new { data = list });
            return str;
        }

        public static async Task<string> PV_UserDefined(string startTime, string endTime, string city , T_PointStoreAdminAuthority auth)
        {
            DateTime dtStart = Convert.ToDateTime(startTime);
            DateTime dtEnd = Convert.ToDateTime(endTime).AddDays(-1);
            TimeSpan ts = dtEnd - dtStart;
            int day = ts.Days;
            if (day==0)
            {
                return await PV_GetOneDay(dtStart, city, auth);
            }
            else
            {
                return await PV_GetNDay(startTime, endTime, city, auth);
            }
        }

        public static async Task<string> UV_GetOneDay(DateTime day, string city, T_PointStoreAdminAuthority auth)
        {
            #region SQL
            string sql = @"
                            select
                                timelist.htime as description,
                                COUNT(DISTINCT F_UserToken)as count
                            from timelist
                            left join (select
                                F_UserToken,
                                F_VisitHour
                            from T_PointStoreVisitLog  
                            WHERE 1=1
                                AND F_VisitTime>={0}
                                AND F_VisitTime<{1}
                                {2}) A on timelist.htime=a.F_VisitHour
                            group by timelist.htime 
                        "; 
            #endregion
            List<Model_Chart> list = new List<Model_Chart>();
            if (auth.F_CityKid != 0)
            {
                city = auth.F_CityName;
            }
            if (!string.IsNullOrWhiteSpace(city))
            {
                string cityPart = " AND F_City={2}";
                sql = string.Format(sql, "{0}", "{1}", cityPart);
                using (var db = new DbTour())
                {
                    list = await db.Sql(sql, day.ToString("yyyy-MM-dd"), day.AddDays(1).ToString("yyyy-MM-dd"), city).ToList<Model_Chart>();
                }
            }
            else
            {
                sql = string.Format(sql, "{0}", "{1}", city);
                using (var db = new DbTour())
                {
                    list = await db.Sql(sql, day.ToString("yyyy-MM-dd"), day.AddDays(1).ToString("yyyy-MM-dd")).ToList<Model_Chart>();
                }
            }         
            string str = Json.ToJsonString(new { data = list });
            return str;
        }

        public static async Task<string> UV_GetNDay(string startTime, string endTime, string city, T_PointStoreAdminAuthority auth)
        {
            #region SQL
            string sql = @"
                        select
                          date(F_VisitTime) as description,
                          COUNT(DISTINCT F_UserToken)as count
                        from T_PointStoreVisitLog
                        WHERE 1=1
                          AND F_VisitTime>={0}
                          AND F_VisitTime<{1}
                         {2}
                        group by date(F_VisitTime)
                        "; 
            #endregion
            List<Model_Chart> list = new List<Model_Chart>();
            if (auth.F_CityKid != 0)
            {
                city = auth.F_CityName;
            }
            if (!string.IsNullOrWhiteSpace(city))
            {
                string cityPart = " AND F_City={2}";
                sql = string.Format(sql, "{0}", "{1}", cityPart);
                using (var db = new DbTour())
                {
                    list = await db.Sql(sql, startTime, endTime, city).ToList<Model_Chart>();
                }
            }
            else
            {
                sql = string.Format(sql, "{0}", "{1}", city);
                using (var db = new DbTour())
                {
                    list = await db.Sql(sql, startTime, endTime).ToList<Model_Chart>();
                }
            }     
            foreach (Model_Chart item in list)
            {
                item.description = item.description.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0].ToString();
            }
            string str = Json.ToJsonString(new { data = list });
            return str;
        }

        public static async Task<string> UV_GetOneYear(string startTime, string endTime, string city , T_PointStoreAdminAuthority auth)
        {
            #region SQL
            string sql = @"
                  select
                    yearlist.ytime as description,
                    COUNT(DISTINCT F_UserToken)as count
                  from yearlist
                  left join(select
                    F_UserToken,
                    F_VisitMonth
                  from T_PointStoreVisitLog  
                  WHERE 1=1
                    AND F_VisitTime>={0}
                    AND F_VisitTime<{1}
                    {2}) A on yearlist.ytime=a.F_VisitMonth
                  group by yearlist.ytime 
                        "; 
            #endregion
            List<Model_Chart> list = new List<Model_Chart>();
            if (auth.F_CityKid != 0)
            {
                city = auth.F_CityName;
            }
            if (!string.IsNullOrWhiteSpace(city))
            {
                string cityPart = " AND F_City={2}";
                sql = string.Format(sql, "{0}", "{1}", cityPart);
                using (var db = new DbTour())
                {
                    list = await db.Sql(sql, startTime, endTime, city).ToList<Model_Chart>();
                }
            }
            else
            {
                sql = string.Format(sql, "{0}", "{1}", city);
                using (var db = new DbTour())
                {
                    list = await db.Sql(sql, startTime, endTime).ToList<Model_Chart>();
                }
            }     
            string str = Json.ToJsonString(new { data = list });
            return str;
        }

        public static async Task<string> UV_UserDefined(string startTime, string endTime, string city, T_PointStoreAdminAuthority auth)
        {
            DateTime dtStart = Convert.ToDateTime(startTime);
            DateTime dtEnd = Convert.ToDateTime(endTime).AddDays(-1);
            TimeSpan ts = dtEnd - dtStart;
            int day = ts.Days;
            if (day == 0)
            {
                return await UV_GetOneDay(dtStart, city,auth);
            }
            else
            {
                return await UV_GetNDay(startTime, endTime,city,auth);
            }
        }

        public static async Task<string> TAG_GetData(string startTime, string endTime, string city , T_PointStoreAdminAuthority auth)
        {
            #region SQL
            string sql = @"
                SELECT taglist.F_ShowName AS description,
                       COUNT(A.F_tag)AS COUNT
                FROM taglist
                LEFT JOIN
                  (SELECT F_tag,
                          F_VisitHour
                   FROM T_PointStoreVisitLog
                   WHERE 1=1
                     AND F_VisitTime>={0}
                     AND F_VisitTime<{1} {2} )A ON taglist.f_showname =a.F_tag
                GROUP BY taglist.F_ShowName
                        "; 
            #endregion
            List<Model_Chart> list = new List<Model_Chart>();
            if (auth.F_CityKid != 0)
            {
                city = auth.F_CityName;
            }
            if (!string.IsNullOrWhiteSpace(city))
            {
                string cityPart = " AND F_City={2}";
                sql = string.Format(sql, "{0}", "{1}", cityPart);
                using (var db = new DbTour())
                {
                    list = await db.Sql(sql, startTime, endTime, city).ToList<Model_Chart>();
                }
            }
            else
            {
                sql = string.Format(sql, "{0}", "{1}", city);
                using (var db = new DbTour())
                {
                    list = await db.Sql(sql, startTime, endTime).ToList<Model_Chart>();
                }
            }     
            string str = Json.ToJsonString(new { data = list });
            return str;
        }       
    }
}
